package com.hdsx.netty.rpcclient.bio;

import com.hdsx.netty.protocol.BasicProtocol;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author 占贤银
 * time 2024/8/9 0:13
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public class BioProxy implements InvocationHandler {

    private int port = 8080;

    private String host = "127.0.0.1";

    public BioProxy() {}
    public BioProxy(String host, int port) {
        this.port = port;
        this.host = host;
    }

    public <T> T create(Class<T> aClazz) {
        return (T) Proxy.newProxyInstance(aClazz.getClassLoader(), new Class[]{aClazz}, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        BasicProtocol basicProtocol = new BasicProtocol();
        basicProtocol.setClassName(method.getDeclaringClass().getName());
        basicProtocol.setMethodName(method.getName());
        basicProtocol.setParameterValues(args);
        basicProtocol.setParameterType(method.getParameterTypes());
        Socket socket = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(this.host, this.port));
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(basicProtocol);
            oos.flush();
            ois = new ObjectInputStream(socket.getInputStream());
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != oos) {
                    oos.close();
                }
                if (null != ois) {
                    ois.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
